from django.shortcuts import render
import datetime
from pyecharts.charts import Bar, Page
from pyecharts.globals import ThemeType
from pyecharts import options as opt
from .models import *
from django.http import HttpResponse
# Create your views here.


def sale_index(request):
    info = OrderInfo.objects.filter(eid='SA42376', process_status='未处理')
    if info.exists():
        return render(request, '../templates/Sales/index.html', {'order': info})
    else:
        return render(request, '../templates/Sales/index.html')


def sale_order(request):
    info = OrderInfo.objects.filter(eid='SA42376', process_status='未处理')
    if info.exists():
        order = info[0]
        goods = OrderDetails.objects.filter(order_id=order.order_id)
        if goods.exists():
            return render(request, '../templates/Sales/order-page.html',
                          {'order': order, 'goods': goods})
    else:
        return render(request, '../templates/Sales/order-page.html')


def order_process(request):
    if request.method == "POST":
        order_id = request.POST["order_id"]
        order_number = request.POST["TotalSum"]
        OrderInfo.objects.filter(order_id=order_id).update(process_status="已处理")
        # order.process_status = "已处理"
        # order.save()
        if float(order_number) < 0:
            # 退货处理订单，规定其总价为负数。
            ReturnInfo.objects.create(
                return_id=f"RET+{order_id}", order=order_id,
                apply_time=OrderInfo.objects.filter(order_id=order_id).order_time,
                process_time=datetime.datetime.now(),
                process_way="退货", retrun_status="已处理")
        return sale_order(request)
    else:
        return sale_order(request)


def deliver_process(request):
    deliver_list = OrderInfo.objects.filter(eid='SA42376', process_status='已处理')
    if deliver_list.exists():
        for order in deliver_list:
            deliver_goods = OrderDetails.objects.filter(order_id=order.order_id)
            for good in deliver_goods:
                StockOut.objects.create(
                    order_id=order.order_id,
                    goods_id=good.goods.goods_id,
                    goods_name=good.goods.goods_name,
                    out_time=datetime.datetime.now(), out_num=good.goods_num)
        deliver_list.update(process_status="已发货")
    return sale_index(request)


def income_process(request):
    income_list = OrderInfo.objects.filter(eid='SA42376', process_status='已发货')
    if income_list.exists():
        # 由于没有实现财务相关内容，此功能仅做保留
        income_list.update(process_status="已结算")
        return sale_index(request)
    else:
        return sale_index(request)


def sales_movement(request):
    goods_list = list()
    goods_number = list()
    goods_sale_sum = list()
    for item in GoodsInfo.objects.all().order_by('-goods_name'):
        goods_list.append(item.goods_name)
        tot_num_for_this_id = 0
        for order in OrderDetails.objects.filter(goods=item.goods_id):
            tot_num_for_this_id += order.goods_num
        goods_number.append(tot_num_for_this_id)
        goods_sale_sum.append(tot_num_for_this_id * item.gprice)
    bar_sum = Bar(init_opts=opt.InitOpts(theme=ThemeType.VINTAGE, width="1600px", height="800px"))
    bar_sum.add_xaxis(goods_list)
    bar_sum.add_yaxis("销售额", goods_sale_sum)
    bar_sum.add_yaxis("销售量", goods_number)
    bar_sum.reversal_axis()
    bar_sum.set_series_opts(label_opts=opt.LabelOpts(position="right", formatter="{b}：{c}"))
    bar_sum.set_global_opts(title_opts=opt.TitleOpts(title="销售额/量对比"),
                            legend_opts=opt.LegendOpts(type_="scroll", orient="vertical"))
    bar_sum.render("templates/Pye_chart/sales_index_movement.html")
    return render(request, "../templates/pye_chart/sales_index_movement.html")
